// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as vscode from "vscode";

// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {
  // Use the console to output diagnostic information (console.log) and errors (console.error)
  // This line of code will only be executed once when your extension is activated
  console.log('Congratulations, your extension "hello-world" is now active!');
  console.log(vscode.window.activeTextEditor?.document.getText());
  // The command has been defined in the package.json file
  // Now provide the implementation of the command with registerCommand
  // The commandId parameter must match the command field in package.json
  let disposable = vscode.commands.registerCommand(
    "hello-world.helloZhuFeng",
    () => {
      // The code you place here will be executed every time your command is executed

      // Display a message box to the user
      //vscode.window.showInformationMessage('Hello World from hello world!');
      openBaidu();
    }
  );
  let insertLog = vscode.commands.registerCommand("my.insertLog", () => {
    const editor = vscode.window.activeTextEditor;
    const selection = editor?.selection;
    const text = editor?.document.getText(selection);
    let logToInsert: string;
    if (/error|err/.test(text!)) {
      logToInsert = `\nconsole.time()\nconsole.error('%c${text}:','color:red;','${text}');\nconsole.timeEnd()\n`;
    } else {
      logToInsert = `\nconsole.time()\nconsole.log('%c${text}:','color:red;','${text}');\nconsole.timeEnd()\n`;
    }
    const lineOfSelectedVar = selection?.active.line || 0;
    editor?.edit(editBuilder => {
      editBuilder.insert(
        new vscode.Position(lineOfSelectedVar + 1, 0),
        logToInsert
      );
    });
  });

  let delLog = vscode.commands.registerCommand("my.delLog", () => {
    const editor = vscode.window.activeTextEditor;
    if (!editor) {
      return;
    }

    let workspaceEdit = new vscode.WorkspaceEdit();
    const document = editor.document;

    const logStatements = getAllLogStatements();

    // 循环遍历每个匹配项的range，并删除
    logStatements.forEach(log => {
      workspaceEdit.delete(document.uri, log);
    });
    // 完成后显示消息提醒
    vscode.workspace.applyEdit(workspaceEdit).then(() => {
      vscode.window.showInformationMessage(
        `${logStatements.length} console.log deleted`
      );
    });
  });
  let removeComments = vscode.commands.registerCommand(
    "my.removeComments",
    function () {
      const editor = vscode.window.activeTextEditor;
      editor!.edit(editBuilder => {
        let text = editor!.document.getText();
        // 正则匹配替换掉注释文本
        text = text
          .replace(
            /((\/\*([\w\W]+?)\*\/)|(\/\/(.(?!"\)))+)|(^\s*(?=\r?$)\n))/gm,
            ""
          )
          .replace(/(^\s*(?=\r?$)\n)/gm, "")
          .replace(/\\n\\n\?/gm, "");
        // 全量替换当前页面文本
        const end = new vscode.Position(editor.document.lineCount + 1, 0);
        editBuilder.replace(
          new vscode.Range(new vscode.Position(0, 0), end),
          text
        );
        // 执行格式化代码操作
        vscode.commands.executeCommand("editor.action.formatDocument");
      });
    }
  );

  context.subscriptions.push(removeComments);
  context.subscriptions.push(insertLog);
  context.subscriptions.push(delLog);
  // context.subscriptions.push(disposable);
}
function getAllLogStatements() {
  const editor = vscode.window.activeTextEditor;
  const document = editor!.document;
  const documentText = document.getText();
  let match;
  const logStatements = [];
  const logRegex = /console.(log|debug|info|warn|error|assert|dir|dirxml|trace|group|groupEnd|time|timeEnd|profile|profileEnd|count)\((.*)\);?/g;
  while ((match = logRegex.exec(documentText))) {
    // 每次匹配到当前的范围--Range
    let matchRange = new vscode.Range(
      document.positionAt(match.index),
      document.positionAt(match.index + match[0].length)
    );
    if (!matchRange.isEmpty)
      // 把Range放入数组
      logStatements.push(matchRange);
  }
  return logStatements;
}
function openBaidu() {
  vscode.window
    .showWarningMessage("要不要去珠峰官网呢", "要", "不要也的要")
    .then(res => {
      if (res === "要") {
        vscode.env.openExternal(
          vscode.Uri.parse("http://www.zhufengpeixun.cn")
        );
      } else {
        openBaidu();
      }
    });
}
// this method is called when your extension is deactivated
export function deactivate() {}
